var http = require('http');
var path = require('path');
var express = require('express');
var ShareDB = require('sharedb');
var WebSocketServer = require('ws').Server;
var otText = require('ot-text');
var WebSocketJSONStream = require('websocket-json-stream');
const db = require('sharedb-mongo')('mongodb://localhost:27017/docBase');

ShareDB.types.map['json0'].registerSubtype(otText.type);
var shareDB = new ShareDB({db});

var app = express();
app.use(express.static(__dirname));
// 只需要css
app.use(express.static(__dirname + '/../node_modules/codemirror/csslib'));

var server = http.createServer(app);
server.listen(7007, function (err) {
  if (err) {
    throw err;
  }
  console.log('Listening on http://localhost:%s', server.address().port);
});

var webSocketServer = new WebSocketServer({server: server});

webSocketServer.on('connection', function (socket) {
  var stream = new WebSocketJSONStream(socket);
  // console.log(stream);
  shareDB.listen(stream);
});
